<?php
namespace Home\Controller;

require_once __ROOT__ . '/vendor/riverslei/payment-4.0/autoload.php';
use Payment\Common\PayException;
use Payment\Client\Query;
use Payment\Client\Notify;   //微信异步回调通知类
use Payment\Common\WxConfig; //返回微信支付配置数据
use Payment\Client\Charge;   //触发调用接口
use Payment\Config;          //配置支付类型

use Lib\Controller\HomeBaseController;

//首页-控制器
class IndexController extends HomeBaseController {

    private $UserModel;         //客户端用户
    private $ServerModel;       //员工（店长）
    private $ServerAddressModel;//员工（店长）
    private $ServerAdminModel;  //电脑后台账户
    private $AccessTokenModel;  //微信token

    private $monthcardModel;    //月卡列表
    private $MonthOrderModel;   //月卡订单表
    private $UsermonthModel;    //用户的月卡记录表
    private $serverNameModel;   //服务项目表
    private $serverPriceModel;  //服务项目价格表
    private $UserCarModel;      //用户车辆信息表

    public function __construct(){
        parent::__construct();
        //获取的model作为私有属性
        $this->UserModel            = D('User');            //客户端用户
        $this->ServerModel          = D('Server');          //员工（店长）
        $this->ServerAddressModel   = D('ServerAddress');   //洗车点
        $this->ServerAdminModel     = D('ServerAdmin');     //电脑后台账户
        $this->AccessTokenModel     = D('wx_access_token'); //微信token


        $this->monthcardModel       = D('monthCard');       //月卡列表
        $this->MonthOrderModel      = D('MonthOrder');      //订单（月卡）
        $this->UsermonthModel       = D('UserMonthcard');   //月卡记录（用户使用）
        $this->serverNameModel      = D('serverName');      //服务项目表
        $this->serverPriceModel     = D('serverPrice');     //服务项目价格表
        $this->UserCarModel         = D('UserCar');         //用户车辆信息表
    }
    public function test(){
            $result = D('carBrand')->where('status = 1')->order('en_letter asc')->select();
            echo json_encode($result);
    }
    /**
     * 微信获取用户信息
     */
    public function getUserInfo(){
        $checkcookieWhere['id'] = cookie('userinfo')['id'];
        $checkUser = $this->UserModel->where($checkcookieWhere)->find();
        $checkServer =  $this->ServerModel->where($checkcookieWhere)->find();
        if(empty($checkUser) && empty($checkUser)){
            cookie('userinfo',null);
            $this->_checkWxLogin();
        }

        if(cookie('userinfo')['id'] == ''){
            $appid = C('WX_APPID');
            $appsecret = C('WX_APPSECRET');
            $code = I('get.code');
            //第一步：获取數據庫的全局access_token 並且判斷是否過期
            $findAccessToken = $this->AccessTokenModel->order('id desc')->find();
            if(!empty($findAccessToken) && $findAccessToken['expires_time'] < time() || empty($findAccessToken)){
                $getUserOpenidUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
                $token = $this->wxCurlPost($getUserOpenidUrl);

                $accessTokenData['wx_access_token'] = $token["access_token"];
                $accessTokenData['create_time'] = time();
                $accessTokenData['expires_time'] = time()+7000;
                $addNewAccessToken = $this->AccessTokenModel->add($accessTokenData);

                cookie('wx_access_token',$token["access_token"],7000);
            }
            else if(!empty($findAccessToken) && $findAccessToken['expires_time'] > time()){
                $token['access_token'] = $findAccessToken['wx_access_token'];

                $expireTime = $findAccessToken['expires_time'] - time();
                cookie('wx_access_token',$token["access_token"],$expireTime);
            }


            //第二步:获取微信用户的openid
            $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
            $oauth2 = $this->wxCurlPost($oauth2Url);

            //第三步:根据全局access_token和openid查询用户信息
            $access_token = $token["access_token"];
            $openid = $oauth2['openid'];
            $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
            $userinfo = $this->wxCurlPost($get_user_info_url);

            //获取jsapi_ticket 全局存
            $get_jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $jsapi_ticket = $this->wxCurlPost($get_jsapi_ticket_url);
            cookie('jsapi_ticket',$jsapi_ticket['ticket']);
            cookie('userinfo',$userinfo);session('userinfo',$userinfo);

            $checkUser = $this->UserModel->where('weixin_openid = "'.$userinfo['openid'].'"')->find();
            $checkServer =  $this->ServerModel->where('weixin_openid =  "'.$userinfo['openid'].'"')->find();
        }else{
            $userinfo = cookie('userinfo');

            $checkUser = $this->UserModel->where('weixin_openid = "'.$userinfo['weixin_openid'].'"')->find();
            $checkServer =  $this->ServerModel->where('weixin_openid =  "'.$userinfo['weixin_openid'].'"')->find();
        }
        if(!empty($checkUser) || !empty($checkServer)){
            if($checkUser){
                //判断用户是否更新的用户名与头像
                if($checkUser['user_name'] != cookie('userinfo')['nickname'] && cookie('userinfo')['nickname']!=''){
                    $updateUserData['user_name'] = cookie('userinfo')['nickname'];
                }
                if($checkUser['weixin_avatar'] != cookie('userinfo')['headimgurl'] && cookie('userinfo')['headimgurl']!=''){
                    $updateUserData['weixin_avatar'] = cookie('userinfo')['headimgurl'];
                }
                //如果修改了用户名与头像则更新数据库
                if(isset($updateUserData)){
                    $this->UserModel->where('id = '.$checkUser['id'])->save($updateUserData);
                    $checkUser['user_name'] = $updateUserData['user_name'];
                    $checkUser['weixin_avatar'] = $updateUserData['weixin_avatar'];
                }
                session('userinfo',null);cookie('userinfo',null);
                session('userinfo',$checkUser);cookie('userinfo',$checkUser);
                redirect(U(MODULE_NAME.'/index/wash_shop_list'));
            }
            else if($checkServer){
                //不需要修改服务端的用户名，因为店长需要修改店铺名称
                if($checkServer['name']!=cookie('userinfo')['nickname'] &&cookie('userinfo')['nickname']!='' && $checkServer['is_shopowner']==0){
                    $updateServerData['name'] = cookie('userinfo')['nickname'];
                }
                if($checkServer['weixin_avatar']!=cookie('userinfo')['headimgurl'] &&cookie('userinfo')['headimgurl']!='' && $checkServer['is_shopowner']==0){
                    $updateServerData['weixin_avatar'] = cookie('userinfo')['headimgurl'];
                }
                if(isset($updateServerData)){
                    $this->ServerModel->where('id = '.$checkServer['id'])->save($updateServerData);
                    $checkServer['name'] = $updateServerData['user_name'];
                    $checkServer['weixin_avatar'] = $updateServerData['weixin_avatar'];
                }
                session('userinfo',null);cookie('userinfo',null);
                session('userinfo',$checkServer);cookie('userinfo',$checkServer);
                redirect(U(MODULE_NAME.'/server/index'));
            }
        }else{
            redirect(U(MODULE_NAME.'/index/select_role'));
        }

    }

    public function register(){
        $type = I('get.type');
        $userinfo = cookie('userinfo');
        if(cookie('userinfo')['id'] != ''){

            $checkUser = $this->UserModel->where('weixin_openid = "'.$userinfo['weixin_openid'].'"')->find();
            $checkServer =  $this->ServerModel->where('weixin_openid =  "'.$userinfo['weixin_openid'].'"')->find();
            if(!empty($checkUser)){
                redirect(U(MODULE_NAME.'/personal/addmycarview',array('is_first'=>'1')));
            }
            else if(!empty($checkServer)){
                if($checkServer['p_id']==0 &&$ $checkServer['is_shopowner']==0 && $$checkServer['is_staff']==0){
                    redirect(U(MODULE_NAME.'/server/select_role'));
                }
                else if($checkServer['p_id']==0 &&$ $checkServer['is_shopowner']==1 && $$checkServer['is_staff']==0){
                    redirect(U(MODULE_NAME.'/server/server_order_list'));
                }
                else if($checkServer['p_id']!=0 &&$ $checkServer['is_shopowner']==0 && $$checkServer['is_staff']==0){
                    redirect(U(MODULE_NAME.'/server/staff_wait'));
                }
                else if($checkServer['p_id']!=0 &&$ $checkServer['is_shopowner']==0 && $$checkServer['is_staff']==1){
                    redirect(U(MODULE_NAME.'/server/washer_order_list'));
                }
            }
        }else{
            //获取完微信用户信息后进行用户注册
            $newUserData['weixin_openid'] = $userinfo['openid'];
            $newUserData['weixin_avatar'] = $userinfo['headimgurl'];

            if($type=='customer'){
                $newUserData['openid']      = $this->checkOpenid(date('YmdHis',time()).rand(1000000,9999999));
                $newUserData['user_name']   = $userinfo['nickname'];
                $newUserData['sex']         = $userinfo['sex'];
                $newUserData['create_time'] = time();

                $addUserResult = $this->UserModel->add($newUserData);

                $newUserData['id'] = $addUserResult;
                session('userinfo',null);cookie('userinfo',null);
                session('userinfo',$newUserData);cookie('userinfo',$newUserData);
                //查询所有注册就送的优惠券列表
                $this->getUserCoupon(1);
                //添加完毕引导用户录入车辆信息
                redirect(U(MODULE_NAME.'/personal/addmycarview',array('is_first'=>'1')));
            }
            else if($type=='server'){
                $newUserData['openid'] = $this->checkOpenid(date('YmdHis',time()).rand(1000000,9999999),$types="server");

                $newUserData['name'] = $userinfo['nickname'];
                $newUserData['p_id'] = -1;
                $newUserData['is_shopowner'] = 0;
                $newUserData['is_staff'] = 0;
                $addServerResult = $this->ServerModel->add($newUserData);
                $newUserData['id'] = $addServerResult;

                $serverAdminData['server_id'] = $addServerResult;
                // $serverAdminData['admin_name'] = 'w_'.rand(100, 999).'_'.$addServerResult;
                $serverAdminResult = $this->ServerAdminModel->add($serverAdminData);

                session('userinfo',null);cookie('userinfo',null);
                session('userinfo',$newUserData);cookie('userinfo',$newUserData);
                //暂时只需要店员的注册
                redirect(U(MODULE_NAME.'/server/staff_wait',array('type'=>'staff')));
                //添加完毕跳转店铺列表页
//                 redirect(U(MODULE_NAME.'/server/select_role'));
            }
        }
    }

    public function checkuserinfo($token,$oauth2){
        //第三步:根据全局access_token和openid查询用户信息
        $access_token = $token["access_token"];
        $openid = $oauth2['openid'];
        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $userinfo = $this->wxCurlPost($get_user_info_url);
        if($userinfo){
            return $userinfo;
        }else{
            $this->checkuserinfo($token, $oauth2);
        }
    }

    public function select_role(){
        cookie();
        $this->display();
    }

    /**
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return string 产生的随机字符串
     */
    public static function getNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }


    /**
     * [wx_config 微信配置-接口]
     * @author xiezy
     * @date   2017-10-18
     * @return [type]     [description]
     */
    private static function wx_config($decode_url){
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $jsapi_ticket            = cookie('jsapi_ticket');  //获取jsapi_ticket
        $configData['appId']     = C('WX_APPID');           //APPID
        $configData['timeStamp'] = time();                  //签名的时间戳
        $configData['nonceStr']  = static::getNonceStr();   //签名的随机串
        $configData['url']       = $decode_url;             //签名的url（需要和当前页面一模一样）
        // $configData['url']       = $url; //签名的url（需要和当前页面一模一样）
        // $configData['url']       = 'https://washcar.zhfancon.com/index/wash_shop_list.html'; //签名的url（需要和当前页面一模一样）
        $ticket = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$configData['nonceStr'].'&timestamp='.$configData['timeStamp'].'&url='.$configData['url'];
        $configData['signature'] = sha1($ticket);           //签名

        return $configData ? $configData : null;
    }

    /**
     * [wx_onMenuShareAppMessage 微信分享给朋友-接口]
     * @author xiezy
     * @date   2017-10-18
     * @return [type]     [description]
     */
    public function wx_onMenuShareAppMessage(){
        $url        = I('post.url');
        $decode_url = urldecode($url);
        /*获取微信配置数据*/
        $data = static::wx_config($decode_url);
        if ($data!=null) {
            $data['title'] = '銘聯洗車'; //分享标题
            $data['desc']  = '洗車一級棒,歡迎豪車過來';   //分享描述
            $data['url']   = $decode_url;    //分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            // $data['url']   = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];    //分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            // $data['url'] = 'https://washcar.zhfancon.com/index/wash_shop_list.html';    //分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            $data['headImgUrl'] = 'http://www.bmw.com.cn/content/dam/bmw/marketCN/bmw_com_cn/bmw_ds2_module_box.png.asset.1481563906324.png'; // 分享图标
            $this->ajaxReturn(array('status'=>1,'info'=>'分享成功','data'=>$data));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'分享失敗','data'=>$data));
        }
    }

    /**
     * [wx_shareFriendAfter 微信分享朋友后-添加用户优惠卷]
     * @author xiezy
     * @date   2017-10-19
     *         flase.为无限制分享新增，true.为有限制分享新增
     * @return [type]     [description]
     */
    public function wx_shareFriendAfter(){
        //分享后新增用户的优惠卷 【0-分享】
        $this->getUserCoupon(0);
        $this->ajaxReturn(array('status'=>1,'info'=>'分享成功,獲得優惠卷'));
            // $this->ajaxReturn(array('status'=>0,'info'=>'分享失敗','data'=>$type));
    }
    /**
     * [wx_openLocation 使用微信内置地图查看位置接口]
     * @author xiezy
     * @date   2017-12-10
     * @return [type]     [description]
     */
    public function wx_openLocation(){
        $url        = I('post.url');
        $decode_url = urldecode($url);
        /*获取微信配置数据*/
        $data = static::wx_config($decode_url);
        if ($data!=null) {
            $data['name'] = '銘聯洗車';                      //位置名
            $data['address']  = '洗車一級棒,歡迎豪車過來';   //地址详情说明
            $data['infoUrl']   = $decode_url;                //在查看位置界面底部显示的超链接,可点击跳转
            $this->ajaxReturn(array('status'=>1,'info'=>'查看成功','data'=>$data));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'查看失敗','data'=>$data));
        }
    }

    /**
     * [map 地图]
     * @author xiezy
     * @date   2017-09-07
     * @return [type]     [description]
     */
    public function map(){
        // $where['p_id'] = 0; //店铺为0 员工为店铺id>0
        $where['lat'] = array('gt',0); //经纬度不能为空，否则将过滤
        $where['lon'] = array('gt',0); //经纬度不能为空，否则将过滤
        //店铺数据
        $shopList = $this->ServerAddressModel->where($where)->select();
        foreach ($shopList as $key => $value) {
            $lat_lon[$key][] = $value['lon'];
            $lat_lon[$key][] = $value['lat'];
        }

        $this->assign('lat_lon',$lat_lon);//分配变量
        $this->assign('list',$shopList);  //分配变量
        $this->display();
    }

    /**
     * [wash_shop_list 【洗车店铺】]
     * @author xiezy
     * @date   2017-09-07
     *         p_id
     *         0 => 店铺
     *         x => x店铺下的员工
     * @return [view]     [首页]
     */
    public function wash_shop_list(){
        //店铺数据
        $shopList = $this->ServerAddressModel->where($where)->order(array('star'=>'desc','status'=>'asc'))->select();
        if (!empty($shopList) ) {
            foreach ($shopList as $key => $value) {
                $shopList[$key]['well'] = range(1,$value['star']);// 星級（1,2,3,4,5）
            }
        }
        $this->assign('list',$shopList);//分配变量
        $this->display('index');
    }

    /**
     * [makeBookTimeList 生成预约时间的json数据]
     * @author xiezy
     * @date   2017-12-06
     * @param  [type]     $orderList [description]
     * @return [type]                [description]
     */
    private static function makeBookTimeList($orderList){
        $bookTimeList   = array();                  //时间段数组
        $timeSlot       = strtotime($orderList['server_end_time'])-strtotime($orderList['server_start_time']);
        $times          = ceil($timeSlot/3600);     //时间段的个数

        $startTimeString   = strtotime( date("Y-m-d ").$orderList['server_start_time'] );
        for ($i=0; $i < $times; $i++) {
            $endTimeString  = strtotime('+'.$orderList['time_interval'].' minute',$startTimeString);
            $startTime      = date("H:i",$startTimeString);
            $endTime        = date("H:i",$endTimeString);
            if ($i==$times-1) {
                $bookTimeList[$startTime.'-'.$orderList['server_end_time']]['start_time']      = $startTimeString;
                $bookTimeList[$startTime.'-'.$orderList['server_end_time']]['book_time']       = $startTime.'-'.$orderList['server_end_time'];
                $bookTimeList[$startTime.'-'.$orderList['server_end_time']]['meanwhile_order'] = $orderList['meanwhile_order'];
            }else{
                $bookTimeList[$startTime.'-'.$endTime]['start_time']      = $startTimeString;
                $bookTimeList[$startTime.'-'.$endTime]['book_time']       = $startTime.'-'.$endTime;
                $bookTimeList[$startTime.'-'.$endTime]['meanwhile_order'] = $orderList['meanwhile_order'];
            }
            $startTimeString = $endTimeString; $endTimeString = '';
        }
        return $bookTimeList;
    }

    /**
     * [wash_shop_info 店铺详情]
     * @author xiezy
     * @date   2017-09-11
     * @return [type]     [description]
     */
    public function wash_shop_info(){
        if (IS_GET) {
            $id     = I('get.id');//获取店铺ID
            $flag   = 1;

            //判断是否可进行详情查看 否则返回店铺列表
            if ( empty($id) ) {
                redirect(U(MODULE_NAME.'/index/wash_shop_list'));
                return false;
            }

            $orderList              = $this->ServerAddressModel->find($id);
            //判断上次修改时间是否小于今天--则重置预约时间段--------- 每天
            if ( date("Ymd",$orderList['update_time'])< date("Ymd",time()) ) {
                $bookTimeList['book_time_list'] = serialize( static::makeBookTimeList($orderList) ); //重置时间段
                $bookTimeList['update_time']    = time();                             //重置时间段的修改时间
                $where['id']                    = $id;                                //洗车点ID
                $this->ServerAddressModel->where($where)->save($bookTimeList);
                $orderList['book_time_list']    = $bookTimeList['book_time_list'];    //更新当前查询的预约时间段
            }
            //判断是否有预约时间段
            if (!empty($orderList['book_time_list'])) {
                $orderList['book_time_list']    = unserialize($orderList['book_time_list']);
                foreach ($orderList['book_time_list'] as $key => $value) {
                    if ($value['start_time']< time() || $value['meanwhile_order']<1) {
                        unset($orderList['book_time_list'][$key]);
                    }
                }
            }
            //取出洗车点的星级排序
            if (!empty($orderList)) {
                $orderList['well']  = range(1,$orderList['star']); //排列店铺星级
            }
            //今天该洗车点是否可预约
            if ( count($orderList['book_time_list'])<1 ) {
                $flag = 0; //不可预约
            }

            $this->assign('flag',$flag);     //今日是否可预约
            $this->assign('list',$orderList);//洗车店详情
            $this->display(); //显示页面
        }
    }

    /**
     * [month_card_view 多个月卡详情]
     * @author xiezy
     * @date   2017-11-28
     * @return [type]     [description]
     */
    public function month_card_list(){
        if (IS_GET) {
            $id = I('get.id');                  //洗车点id

            //月卡列表
            $where['server_id'] = -1;
            $where['status']    = 1;            //【状态】后台控制是否展示
            $monthcardList = $this->monthcardModel->where($where)->select();
            if (!empty($monthcardList)) {
                foreach ($monthcardList as $key => $value) {
                    $monthcardList[$key]['server_name_list'] = unserialize($value['server_name_list']);
                }
            }
            //展示各种【月卡价格和服务内容】
            $this->assign('address_id',$id);
            $this->assign('list',$monthcardList);
            $this->display(); //显示页面
        }
    }

    /**
     * [pay_month_view 购买月卡--付款页面]
     * @author xiezy
     * @date   2017-11-28
     * @return [type]     [description]
     */
    public function month_card_view(){
        if (IS_GET) {
            $month_id   = I('get.month_id');    //月卡id
            $address_id = cookie('address_id'); //洗车点id

            //1.根据月卡id查询一个月卡详情
            $where['server_id'] = -1;
            $where['id'] = $month_id;
            $monthcardList = $this->monthcardModel->where($where)->find();
            if (!empty($monthcardList)) {
                $monthcardList['server_name_list'] = unserialize($monthcardList['server_name_list']);
            }

            //付款前展示月卡价格和服务内容
            $this->assign('address_id',$address_id);
            $this->assign('list',$monthcardList);
            $this->display(); //显示页面
        }
    }

    /**
     * [pay_month_card 付款月卡]
     * @author xiezy
     * @date   2017-11-28
     * @return [type]     [description]
     */
    public function pay_month_card(){
        $ordersn        = date('YmdHis') . str_pad(mt_rand(1, 999999999), 9, '0', STR_PAD_LEFT);  //生成订单号
        $month_id       = I('post.month_id');
        $address_id     = I('post.address_id');

        //1.准备好【月卡订单表数据】 和 【购买月卡记录表数据】（用户） 存入cookie
        $where['id']    = $month_id;
        $monthcardList  = $this->monthcardModel->where($where)->find(); //购买的月卡详情
        //存入cookie准备订单数据--还差【weixin_month_ordersn】【pay_time】
        $monthOrderData['openid']           = cookie('userinfo')['openid'];         //用户openid（自定义）
        $monthOrderData['month_ordersn']    = $ordersn;                             //月卡订单号
        $monthOrderData['month_card_id']    = $month_id;                            //月卡id
        $monthOrderData['address_id']       = $address_id;                          //洗车点id
        $monthOrderData['month_price']      = $monthcardList['month_card_total'];   //购买月卡价格 -- 单位：元
        $monthOrderData['create_time']      = time();

        $userMonthData['openid']            = $monthOrderData['openid'];            //用户openid
        $userMonthData['address_id']        = $monthOrderData['address_id'];        //洗车点id
        $userMonthData['month_card_id']     = $monthOrderData['month_card_id'];     //月卡id
        $userMonthData['use_month_card']    = $monthcardList['server_name_list'];   //月卡服务内容
        $userMonthData['create_time']       = time();                               //创建时间
        $userMonthData['last_time']         = time();                               //上次使用时间
        $userMonthData['deadline']          = time()+(30*86400);                    //月卡的过期时间

        cookie('monthcardList',$monthcardList);             //月卡详情
        cookie('month_order_ready_data',$monthOrderData);
        cookie('user_month_ready_data',$userMonthData);

        //2.组装微信调用支付数据
        $readyData['body']              = '月卡';
        $readyData['subject']           = '購買月卡';
        $readyData['order_no']          = $monthOrderData['month_ordersn'];
        $readyData['timeout_express']   = time() + 600;
        $readyData['amount']            = $monthOrderData['month_price'];
        $readyData['return_param']      = 'lin';                                    //返回的参数
        $readyData['openid']            = cookie('userinfo')['weixin_openid'];      //下单需要的 微信openid

        //3.申请微信支付--统一下单
        $callpayData = static::payforWx($readyData);
        if (!empty($callpayData['package'])) {
            $jsapi_ticket = cookie('jsapi_ticket'); //获取jsapi_ticket
            $ticket = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$callpayData['nonceStr'].'&timestamp='.$callpayData['timeStamp'].'&url=https://washcar.zhfancon.com/index/month_card_view/month_id/'.$month_id.'.html';
            $callpayData['ordersn']   = $monthOrderData['month_ordersn'];   //帶商戶訂單號
            $callpayData['signature'] = sha1($ticket);                      //签名
            $this->ajaxReturn(array('status'=>1,'info'=>'預支付package成功','data'=>$callpayData));
        }else{
            //預支付生成失败,删除数据库订单资料,并关闭订单。
            $this->ajaxReturn(array('status'=>0,'info'=>'預支付package失敗','data'=>'error'));
        }
    }

    /**
     * [dsfs 购买月卡--支付成功页面]
     * @author xiezy
     * @date   2017-11-29
     * @return [type]     [description]
     */
    public function showAfterMonthcardPay(){
        $ordersn                = I('get.ordersn');

        //1.微信支付查询订单，成功则添加订单数据
        $data = static::queryforWx($ordersn);
        if ( !empty($data['trade_state']) && $data['trade_state']=='SUCCESS' ) {
            //线上支付需要的订单数据
            $monthOrderData     = cookie('month_order_ready_data'); cookie('month_order_ready_data',null);
            $userMonthData      = cookie('user_month_ready_data');  cookie('user_month_ready_data',null);
            $monthcardList      = cookie('monthcardList');          cookie('monthcardList',null);
            $monthOrderData['pay_time']             = strtotime($data['time_end']);     //支付完成时间
            $monthOrderData['weixin_month_ordersn'] = $data['transaction_id'];          //微信支付订单号
            $newMonthcardId = $this->MonthOrderModel->filter('strip_tags')->add($monthOrderData);          //filter('strip_tags') 过滤标签等非法输入
            $newUserMonthId = $this->UsermonthModel->filter('strip_tags')->add($userMonthData);           //filter('strip_tags') 过滤标签等非法输入
        }

        $this->assign('data',$data);
        $this->assign('monthcardList',$monthcardList);
        $this->assign('monthOrderData',$monthOrderData);
        $this->assign('userMonthData',$userMonthData);
        $this->display();
    }

    /**
     * [gopay 下单页面]
     * @author xiezy
     * @date   2017-09-11
     * @return [view]     [gopay]
     */
    public function gopay(){
        $id     = I('get.id');//获取洗车点ID

        //判断是否可进行下单操作 否则返回店铺列表
        if ( empty($id) ) {
            redirect(U(MODULE_NAME.'/index/wash_shop_list'));
            return false;
        }
        //1.查询是否购买过月卡
        $usermonthWhere['openid']           = cookie('userinfo')['openid']; //openid
        $usermonthWhere['address_id']       = $id;                          //每家洗车点 的月卡都可以拥有一张
        $usermonthWhere['deadline']         = array('NEQ','');              //过期时间
        $usermonthWhere['deadline']         = array('gt',time());           //过期时间
        $usermonthWhere['use_month_card']   = array('NEQ','NULL');
        $usermonthWhere['use_month_card']   = array('NEQ','');
        $UsermonthData = $this->UsermonthModel->where($usermonthWhere)->select();

        if (!empty($UsermonthData)) {
            $this->assign('have_monthcard',0);//不允许购买月卡
        }else{
            $this->assign('have_monthcard',1);//允许购买月卡
        }
        //该洗车点详情
        $orderList = $this->ServerAddressModel->find($id);

        $this->assign('list',$orderList);//分配变量
        $this->display(); //显示页面
    }

    /**
     * [once_card_list 单次卡的服务内容展示]
     * @author xiezy
     * @date   2017-11-29
     * @return [type]     [description]
     */
    public function once_card_list(){
        $id     = I('get.id');//获取洗车点ID

        //1.服务价格表
        $where['server_address_id'] = $id;
        $serverPriceData = $this->serverPriceModel->where($where)->select();
        foreach ($serverPriceData as $key => $value) {
            $serverWhere['id']= $value['server_name_id'];
            $serverName = $this->serverNameModel->where($serverWhere)->getField('server_name');
            $serverPriceData[$key]['server_name'] = $serverName;
        }

        //2.用户的月卡服务项目
        $usermonthWhere['openid']           = cookie('userinfo')['openid'];
        $usermonthWhere['address_id']       = $id;
        $usermonthWhere['deadline']         = array('NEQ','');
        $usermonthWhere['deadline']         = array('gt',time());
        $usermonthWhere['use_month_card']   = array('NEQ','NULL');
        $usermonthWhere['use_month_card']   = array('NEQ','');
        $UsermonthData = $this->UsermonthModel->where($usermonthWhere)->find();

        //3.查出用户默认车辆类型
        $userCarWhere['openid']             = cookie('userinfo')['openid'];
        $userCarWhere['default']            = 1;
        $userCarType   = $this->UserCarModel->where($userCarWhere)->getField('type');   //（1=>五座車,2=>七座車,3=>其他車）

        // p($userCarType);
        // p($UsermonthData);
        // p($serverPriceData);die;
        //展示月卡服务
        if (!empty($UsermonthData)) {
            $UsermonthData['use_month_card']    = unserialize($UsermonthData['use_month_card']);
            $this->assign('UsermonthData',$UsermonthData);      //用戶在該洗車點擁有的【月卡服務】
        }

        $this->assign('address_id',$id);//分配变量
        $this->assign('userCarType',$userCarType);              //用户的车辆类型=>服务价格
        $this->assign('serverPriceData',$serverPriceData);      //洗車點擁有的【單次服務】
        $this->display(); //显示页面
    }

    /**
     * [confirm 确认订单]
     * @author xiezy
     * @date   2017-09-12
     * @return [type]     [返回页面]
     */
    public function confirm(){
        $userinfo       = cookie('userinfo');       //用户信息
        $once_server    = cookie('once_server'); cookie('once_server',null);  //勾选的单次服务IDs
        $month_server   = cookie('month_server');cookie('month_server',null); //勾选的月卡服务

        $id             = I('get.id');//获取洗车点ID

        // 判断是否可进行订单操作
        if ( empty($userinfo['openid']) ) {
            redirect( U(MODULE_NAME.'/index/once_card_list',array('id'=>$id)) );
        }else{
            //判断是否绑定我的爱车，否则不让进入支付页面
            $ucWhere['openid'] = $userinfo['openid'];
            $result = $this->UserCarModel->where($ucWhere)->find();
            if (empty($result)) {
                redirect( U(MODULE_NAME.'/personal/addmycarview') );
            }
        }


        //1.用户信息
        $user                = M('user');   //获取用户联系方式
        $userWhere['openid'] = $userinfo['openid'];
        $userData            = $user->where( $userWhere )->find();
        //2.查询当前用户的爱车--数据
        $where['default']    = 1; //默认爱车
        $where['openid']     = $userinfo['openid']; //当前用户
        $usercarData         = $this->UserCarModel->where($where)->find();

        //3.单次收费服务--数据
        $wash_server_name    = ''; //服务名累加

        $total_price         = 0; //单次服务的总价格
        if ( !empty($once_server) ) {
            $once_serverIds = trim($once_server,',');
            $once_serverIds = explode(',', $once_serverIds);

            //服务价格表（勾选的单次服务IDs）
            $where['id']     = array('in',$once_serverIds);
            $serverPriceData = $this->serverPriceModel->where($where)->select();
            if (!empty($serverPriceData)) {
                foreach ($serverPriceData as $key => $value) {
                    //1.勾选服务各价格累加
                    switch ($usercarData['type']) {
                        case '1':
                            $total_price+= $value['five_price'];
                            break;
                        case '2':
                            $total_price+= $value['seven_price'];
                            break;
                        case '3':
                            $total_price+= $value['other_price'];
                            break;
                    }
                    //2.勾选的服务名累加
                    $washWhere['id']    = $value['server_name_id'];
                    $serverName         = $this->serverNameModel->where($washWhere)->getField('server_name');
                    $wash_server_name   .=$serverName.',';
                }
            }
        }

        //4.记录用户的月卡使用记录
        $serverNameArr = array();
        if ( !empty($month_server) ) {
            $month_serverJson = trim($month_server,',');
            $month_serverJson = explode(',', $month_serverJson);

            if (!empty($month_serverJson['0']) ) {
                foreach ($month_serverJson as $key => $value) {
                    if ($key>0) {
                        $ret = explode('|', $value);
                        //月卡的服务次数 > 0 才存进用户的月卡使用记录表
                        if ( $ret['2']>0 ) {
                            $serverNameArr[]   = array('id'=>$ret['0'],'server_name'=>$ret['1'],'server_times'=>$ret['2']);
                        }
                        //月卡中勾选的服务名累加
                        if ( $ret['3']=='checked' ) {
                            $wash_server_name .= $ret['1'].',';
                        }
                    }
                }
            }else{
                $serverNameArr = '';
            }
        }
        //4.5 存该用户的月卡记录
        $user_month_server['id'] = $month_serverJson['0'];
        $user_month_server['use_month_card'] = serialize( $serverNameArr );
        cookie('user_month_server',$user_month_server);
        cookie('wash_server_names',$wash_server_name);

        //5.洗车点详情
        $serverAddressList   = $this->ServerAddressModel->find($id);

        $serverAddressList['phone']           = $userData['phone'];               //获取用户的联系方式
        $serverAddressList['card_type']       =  1; //存
        $serverAddressList['type']            =  '單次服務'; //展示
        $serverAddressList['total_price']     = $total_price; //存

        //判断是否有预约时间段
        if (!empty($serverAddressList['book_time_list'])) {
            $serverAddressList['book_time_list']    = unserialize($serverAddressList['book_time_list']);
            foreach ($serverAddressList['book_time_list'] as $key => $value) {
                if ($value['start_time']< time() || $value['meanwhile_order']<1) {
                    unset($serverAddressList['book_time_list'][$key]);
                }
            }
        }

        //6.获取我的优惠卷
        $coupon_data = $this->getcoupon();

        $this->assign('coupon_data',$coupon_data);  //我的优惠卷
        $this->assign('uc_data',$usercarData);      //我的爱车all data
        $this->assign('list',$serverAddressList);   //店铺信息与订单
        $this->display();
    }

    /**
     * [getcoupon 下单页面-获取当前用户可使用的优惠卷]
     * @author xiezy
     * @date   2017-10-11
     * @return [type]     [description]
     */
    public function getcoupon(){
        $result = array();
        //用户使用的优惠卷
        $where['member_id'] = cookie('userinfo')['id'];
        $applyCouponData = M('applyCoupon')->where($aWhere)->select();
        //用户拥有表该去掉的id
        $userCouponIDS = array();
        if (!empty($applyCouponData)) {
            foreach ($applyCouponData as $k => $v) {
                $userCouponIDS[] = $v['user_coupon_id'];
            }
            $uWhere['id'] = array('not in',$userCouponIDS);
        }
        //用户拥有的优惠卷
        $uWhere['member_id'] = array('in',array(-1,cookie('userinfo')['id']));
        $userCouponData = M('userCoupon')->where($uWhere)->select();

        foreach($userCouponData as $key =>$val){
            $checkCouponWhere['id'] = $val['coupon_id'];
            $checkCouponInfo = M('coupon')->where($checkCouponWhere)->find();
            if($checkCouponInfo['end_time'] < time()){
                unset($userCouponData[$key]);
            }else{
                $userCouponData[$key]['price'] = $checkCouponInfo['price'];
            }
        }
        return $userCouponData;
    }

    /**
     * [confirmOrder 下订单]
     * @author xiezy
     * @date   2017-09-12
     * @return [type]     [description]
     */
    public function confirmOrder(){
        $id           = I('post.id');          //洗车店ID
        $car_id       = I('post.car_id');      //车牌对应ID
        $coupon       = I('post.coupon');      //优惠卷id,用户拥有优惠卷id
        $pay_type     = I('post.pay_type');    //付款类型 （线上或线下）
        $card_type    = I('post.card_type');   //洗车卡类型
        $book_time    = I('post.book_time');   //洗车备注
        $remarks      = I('post.remarks');     //洗车备注
        $total_price  = I('post.total_price'); //总价
        $phone        = I('post.phone');       //联系方式
        $userinfo     = cookie('userinfo');    //微信用户信息

        //判断是否可进行确认订单操作,否则跳转到店铺列表,重新下单
        if ( empty($userinfo) || empty($id) || empty($car_id) || $total_price<0) {
            redirect(U(MODULE_NAME.'/index/wash_shop_list'));
            return false;
        }

        $danhao = date('Ymd') . str_pad(mt_rand(1, 9999999999999), 13, '0', STR_PAD_LEFT);  //生成订单号

        if($card_type=='1'){
            $saveData['end_time'] = strtotime(date('Y-m-d', time()))+86400; //一天
            $type                 = '次卡消費';
        }

        //判断是否有优惠卷
        if (!empty($coupon)) {
            $couponArray  = explode(',', $coupon);
            $userCouponId = $couponArray[0];
            $coupon_id    = $couponArray[1];
        }

        //1.输入订单表order 需要的信息 【订单】
        $order                          = M('order');
        $saveData['ordersn']            = $danhao;                              // 自动生成订单号
        $saveData['server_id']          = -1;                                   // 洗车员工 id
        $saveData['server_address_id']  = $id;                                  // 洗车点   id
        $saveData['user_coupon_id']     = !empty($userCouponId)?$userCouponId:'';// 优惠卷类型id
        $saveData['coupon_id']          = !empty($coupon_id) ? $coupon_id : ''; // 优惠卷类型id
        $saveData['pay_type']           = $pay_type;                            // 付款类型
        $saveData['card_type']          = $card_type;                           // 洗车卡类型
        $saveData['book_time']          = $book_time;                           // 预约时间 为两个小时后
        $saveData['create_time']        = time();                               // 创建时间
        $saveData['price']              = $total_price;                         // 总价
        $saveData['wash_server_name']   = cookie('wash_server_names');          // 勾选的服务  （逗号分隔,）
        $saveData['wash_status']        = 0;                                    // 未安排
        $saveData['order_phone']        = $phone;                               // 订单联系方式
        $saveData['remarks']            = $remarks ? $remarks :'';              // 洗车备注

        //2.输入订单order_info 需要的信息 【订单详情】
        $orderInfo               = M('orderInfo');
        $saveData['openid']      = $userinfo['openid'];// 当前登录者id
        $saveData['user_car_id'] = $car_id;         // 爱车ID

        //3.输入订单wash_log 需要的信息 【洗车日志】
        $washLog                 = M('washLog');
        $logWhere['ordersn']     = $saveData['ordersn'];

        //4.是否使用优惠卷
        $coupon_price = 0; //默认不使用为0
        if (!empty($coupon_id)) {
            $result = M('coupon')->find($coupon_id); //找到绑定的优惠卷价格
            $coupon_price = $result['price'];
        }
        // 最终价格为0--就不采用微信支付
        if ($saveData['price']==0 || $saveData['price'] <= $coupon_price) {
            $saveData['pay_time']       = time();                               //支付完成时间
            $saveData['status']         = 1;                                    //微信支付状态 （已付款）
        }

        /*最终价格为0的情况*/
        if ( $saveData['price'] ==0 || $saveData['price'] <= $coupon_price) {
            $order->data($saveData)->filter('strip_tags')->add(); //filter('strip_tags') 过滤标签等非法输入
            $orderInfo->data($saveData)->filter('strip_tags')->add(); //filter('strip_tags') 过滤标签等非法输入
            $washLog->data($logWhere)->filter('strip_tags')->add(); //filter('strip_tags') 过滤标签等非法输入
            $this->ajaxReturn( array('status'=>2,'info'=>'下單成功','data'=>array('ordersn'=>$saveData['ordersn'],'type'=>1) ) );
        }else if( $saveData['price'] >0 ){
            //存入cookie准备订单数据
            cookie('order_ready_data',$saveData);
            if ($saveData['price']-$coupon_price>0 && $saveData['price']-$coupon_price < 0.01) {
                $amount = 0.01;
            }else{
                $amount = $saveData['price']-$coupon_price;
            }
            //5.组装微信调用支付数据
            $readyData['body']              = '洗车';
            $readyData['subject']           = $readyData['body'].$type;
            $readyData['order_no']          = $saveData['ordersn'];
            $readyData['timeout_express']   = time() + 600;
            $readyData['amount']            = $amount;                            //微信支付金额
            $readyData['return_param']      = 'lin';
            $readyData['openid']            = cookie('userinfo')['weixin_openid'];
            $callpayData = static::payforWx($readyData);
            if (!empty($callpayData['package'])) {
                $jsapi_ticket = cookie('jsapi_ticket'); //获取jsapi_ticket
                $ticket = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$callpayData['nonceStr'].'&timestamp='.$callpayData['timeStamp'].'&url=https://washcar.zhfancon.com/index/confirm/id/'.$id.'.html';
                $callpayData['ordersn']   = $saveData['ordersn'];   //帶商戶訂單號
                $callpayData['signature'] = sha1($ticket);          //签名
                $callpayData['type']      = 2;                      //微信支付为类型2
                $this->ajaxReturn(array('status'=>1,'info'=>'預支付package成功','data'=>$callpayData));
            }else{
                //預支付生成失败,删除数据库订单资料,并关闭订单。
                $this->ajaxReturn(array('status'=>0,'info'=>'預支付package失敗','data'=>'error'));
            }
        }

    }

    /**
     * [payforWx 微信调起支付接口所需参数]
     * @author xiezy
     * @date   2017-09-26
     * @param  [array]     $saveData [需要保存的数据]
     * @return [type]                [description]
     */
    private static function payforWx($readyData){

        date_default_timezone_set('Asia/Shanghai');

        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        // 订单信息
        $payData = [
            'body'              => $readyData['body'],              /*商品描述*/
            'subject'           => $readyData['subject'],           /*商品详情*/
            'order_no'          => $readyData['order_no'],          /*商户订单号*/
            'timeout_express'   => $readyData['timeout_express'],   /*表示必须 600s 内付款*/
            'amount'            => $readyData['amount'],            /*单位：元*/
            'return_param'      => 'lin',                           /*异步通知原样返回数据*/
            'client_ip'         => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',  // 客户地址
            'terminal_id'       =>'WEB',                            /*统一下单-类型*/
            'openid'            => $readyData['openid'],            /*微信用户openid*/
            // 'product_id' => '123',
        ];
        try {
            $ret = Charge::run(Config::WX_CHANNEL_PUB, $wxConfig, $payData);
        } catch (PayException $e) {
            return $e->errorMessage();
            exit;
        }

        return $ret;
    }

    /**
     * [queryforWx 微信查询订单接口]
     * @author xiezy
     * @date   2017-09-26
     * @param  [string]     $ordersn [商户订单号]
     * @return [array]               [查询订单结果集]
     */
    private static function queryforWx($ordersn){

        date_default_timezone_set('Asia/Shanghai');

        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        $data = [
            'out_trade_no' => $ordersn,   //商户订单号
            // 'transaction_id' => '4200000015201709254188440403'  //微信订单号
        ];

        try {
            $ret = Query::run(Config::WX_CHARGE, $wxConfig, $data);
        } catch (PayException $e) {
            echo $e->errorMessage();
            exit;
        }

        return $ret;
    }

    /**
     * [delOrdersnData 删除订单号的关联数据]
     * @author xiezy
     * @date   2017-09-20
     * @param  [varchar]     $ordersn [商户订单号]
     * @return               []
     */
    private static function delOrdersnData($ordersn){
        $where['ordersn'] = $ordersn;
        $order                   = M('order');
        $orderInfo               = M('orderInfo');
        $washLog                 = M('washLog');
        $order->where($where)->delete();
        $orderInfo->where($where)->delete();
        $washLog->where($where)->delete();
    }

    /**
     * [showAfterPay 单次卡--支付成功页面]
     * @author xiezy
     * @date   2017-09-25
     * @return [type]     [description]
     */
    public function showAfterPay(){
        $ordersn                    = I('get.ordersn');
        $type                       = I('get.type');
        $order                      = M('order');
        $orderInfo                  = M('orderInfo');
        $washLog                    = M('washLog');
        $server                     = M('server');
        $coupon                     = M('coupon');     //优惠卷类
        $where['ordersn']           = $ordersn;        //商户订单号

        if ($type ==2) {
            //1.微信支付查询订单，成功则添加订单数据
            $data = static::queryforWx($ordersn);
            if ( !empty($data['trade_state']) && $data['trade_state']=='SUCCESS' ) {
                //线上支付需要的订单数据
                $saveData                   = cookie('order_ready_data'); cookie('order_ready_data',null);
                $saveData['pay_time']       = strtotime($data['time_end']); //支付完成时间
                $saveData['status']         = 1;                            //微信支付状态
                $saveData['weixin_ordersn'] = $data['transaction_id'];      //微信支付订单号
                $order->data($saveData)->filter('strip_tags')->add(); //filter('strip_tags') 过滤标签等非法输入
                $orderInfo->data($saveData)->filter('strip_tags')->add(); //filter('strip_tags') 过滤标签等非法输入
                $washLog->data($where)->filter('strip_tags')->add(); //filter('strip_tags') 过滤标签等非法输入
            }
        }

        //2.查詢當前訂單號-【訂單詳情和店铺详情】
        $orderData      = $order->where($where)->find();                                        //订单內容
        $orderInfoData  = $orderInfo->where($where)->find();                                    //订单详情內容
        $userCarData    = $this->UserCarModel->find($orderInfoData['user_car_id']);             //訂單車牌信息
        $ServerAddress  = $this->ServerAddressModel->find($orderData['server_address_id']);     //店铺信息

        $orderData['pay_time']  = date('Y-m-d H:i:s',$orderData['pay_time']);

        //3.更新--该洗车点的【最新预约时间段】
        if ($type ==1) {
            $ServerAddress['book_time_list'] = unserialize($ServerAddress['book_time_list']);
            foreach ($ServerAddress['book_time_list'] as $key => $value) {
                //该订单的预约时间 次数-1
                if ($key==$orderData['book_time']) {
                    if ($value['meanwhile_order']>1) {
                        $ServerAddress['book_time_list'][$key]['meanwhile_order'] = $value['meanwhile_order']-1;
                    }else{
                        unset($ServerAddress['book_time_list'][$key]);
                    }
                }
            }
            if (!empty($ServerAddress['book_time_list']) && is_array($ServerAddress['book_time_list'])) {
                $book_time_list = serialize($ServerAddress['book_time_list']);
                $this->ServerAddressModel->find($orderData['server_address_id']);
                $this->ServerAddressModel->book_time_list = $book_time_list;
                $this->ServerAddressModel->save();
            }
        }

        //4.更新--用户的月卡记录
        $user_month_server = cookie('user_month_server');
        if (!empty($user_month_server)) {
            $this->UsermonthModel->find($user_month_server['id']);
            $this->UsermonthModel->use_month_card = $user_month_server['use_month_card'];
            $this->UsermonthModel->save();
        }

        //5.处理当前订单的【优惠卷】,以及展示实际付款金额
        if (isset($orderData['coupon_id']) && $orderData['coupon_id'] >0 ){
            $coupon_data = $coupon->find($orderData['coupon_id']);               //优惠卷类型
            if ($orderData['price']-$coupon_data['price']>0 && $orderData['price']-$coupon_data['price'] < 0.01) {
                $amount = 0.01;
            }else if($orderData['price']-$coupon_data['price'] <0 ){
                $amount = 0;
            }else{
                $amount = $orderData['price']-$coupon_data['price'];
            }
            $orderData['fact_price'] = $amount; //实际付款金额

            //用户使用的优惠卷
            $applyData['server_id']         = -1;
            $applyData['member_id']         = cookie('userinfo')['id'];
            $applyData['coupon_id']         = $orderData['coupon_id'];
            $applyData['user_coupon_id']    = $saveData['user_coupon_id'];
            $applyData['order_id']          = $orderData['id'];
            $applyCouponData = M('applyCoupon')->data($applyData)->filter('strip_tags')->add();

            // $where['status']     = 1; //可用的
            // $where['member_id']  = cookie('userinfo')['id'];
            // $where['coupon_id']  = $orderData['coupon_id'];
            // $couData['order_id'] = $orderData['id'];
            // $couData['status']   = 0;
            // $result = M('useCoupon')->where($where)->limit(1)->save($couData);
        }else{
            $orderData['fact_price'] = $orderData['price'];
        }

        //4.查询支付状态是否成功，则推送模板消息
        static::templateSendForPay($orderData,$ServerAddress,$userCarData,$type);

        $this->assign('order',$orderData);
        $this->assign('server',$ServerAddress);
        $this->display();
    }

    /**
     * [templateSend 推送模板消息（支付成功）]
     * @author xiezy
     * @date   2017-09-26
     * @return [type]     [description]
     */
    private static function templateSendForPay($orderData,$serverData,$userCarData,$type){
        $userinfo   = cookie('userinfo');    //微信用户信息
        //推送后模板消息的链接
        $orderurl   = 'https://washcar.zhfancon.com/Personal/order_list/type/pay_success.html';
        // 模板id
        $templateid = 'qKba0zP-yE7a0W5PiARNSGl4TB3SgojYTdUF1JjcJXE'; //支付成功通知

        $title      = $type==1 ? "下單成功通知" : "支付成功通知";
        $remark     = $type==1 ? "下單完成"     : "訂單支付完成";
        $pdata=array(
                'first'=>array(
                    'value'=>urlencode($title),
                    "color"=>"#000000"
                ),
                'keyword1'=>array( //订单编号
                    'value'=>$orderData['ordersn'],
                    'color'=>"#FF0000"
                ),
                'keyword2'=>array( //車牌
                    'value'=>$userCarData['license_plate'],
                    'color'=>"#000000"
                ),
                'keyword3'=>array( //消费金额
                    'value'=>$orderData['fact_price'].'元',
                    'color'=>"#000000"
                ),
                'keyword4'=>array( //消费门店
                    'value'=>$serverData['address_name'],
                    'color'=>"#000000"
                ),
                'keyword5'=>array( //消费时间
                    'value'=>$orderData['pay_time'],
                    'color'=>"#000000"
                ),
                'remark'=>array(
                    'value'=>$remark.",如有問題請致電853-65233007或直接在微信留言,小銘將在第一時間爲你服務!",
                    'color'=>"#FF8800"
                ),
            );
        //推送
        self::pushWXMessage($userinfo, $pdata,$templateid,$orderurl);
    }

    /**
     * [notify_info 微信支付成功后的 异步回调的url]
     * @author xiezy
     * @date   2017-09-25
     *         需要返回 return_code 为success 方可终止微信发送通知
     * @return [string]     [success]
     */
    public function notify_info(){
        //引入商户回调业务处理类
        require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/testNotify.php';
        //引入配置文件
        $wxConfig = require_once __ROOT__ . '/vendor/riverslei/payment-4.0/examples/wxconfig.php';

        //业务类
        $callback = new TestNotify();

        $type = 'wx_charge'; //微信支付

        try {
            // $retData = Notify::getNotifyData($type, $config);// 获取第三方的原始数据，未进行签名检查
            $ret = Notify::run($type, $wxConfig, $callback);// 处理回调，内部进行了签名检查
        } catch (PayException $e) {
            echo $e->errorMessage();
            exit;
        }

        echo 'SUCCESS';
    }

    public function gift_coupon(){
        $this->display();
    }

    /**
     * [mymoney 我的钱包]
     * @author xiezy
     * @date   2017-09-11
     * @return [type]     [description]
     */
    public function mymoney() {
        $this->display();
    }

    /**
     * [recommend 我推荐的好友]
     * @author xiezy
     * @date   2017-09-11
     * @return [type]     [description]
     */
    public function recommend(){
        $this->display();
    }



}
